package com.speily.mythreadpool;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test {

    /**
     * java自带线程池
     */
    @org.junit.Test
	public void test02(){
        BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 5, TimeUnit.SECONDS,
                queue, new ThreadPoolExecutor.AbortPolicy());

        // 向线程池里面扔任务
        for (int i = 0; i < 10; i++) {
            System.out.println("当前线程池大小[" + threadPool.getPoolSize() + "],当前队列大小[" + queue.size() + "]");

            threadPool.execute(new MyThread("Thread" + i));
        }
        // 关闭线程池
        threadPool.shutdown();
    }

    private class MyThread implements Runnable {

        private String name;


        public MyThread(String s) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000);

                System.out.println(name + " finished job!") ;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 自定义线程池
     */
    public static void main(String[] args) throws InterruptedException {
        //初始化线程池
        DefaultThreadPool defaultThreadPool = new DefaultThreadPool(5);
        //main线程休眠5s
        Thread.sleep(5000L);

        //创建20个job
        for (int i=0;i<20;i++){
            Job job = new Job(i);
            defaultThreadPool.execute(job);
        }
    }
}
